<template>
  <div class="list">
    <Breadcrumb></Breadcrumb>
    <div class="head">
      
      <div class="search">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="产品名称">
                <el-input v-model="formInline.pname" placeholder="填写名称" ref="pnameInput"></el-input>
              </el-form-item>
              <el-form-item label="添加时间">
                <el-date-picker
                  v-model="formInline.time"
                  type="date"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
      </div>
      <div class="managegoods">
        <el-row>
           <el-button type="warning" size="small" @click="addgoods" icon="el-icon-circle-plus-outline">添加产品</el-button>
          <el-button type="danger" size="small" @click="removegoods" icon="el-icon-delete">批量删除</el-button>
        </el-row>
      </div>
    </div>
    <div class="table">
      <el-table
        height="500"
        :v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
         <el-table-column
          prop="id"
          label="商品ID"
          width="120">
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="title" label="商品名称" width="120">
          <template slot-scope="scopeData">

            <el-popover
              placement="top-start"
              content="查看"
              width="20"
              trigger="hover">
              <span slot="reference" @click="handleDetail(scopeData.$index, scopeData.row)" class="ptitle" >{{scopeData.row.title}}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="商品价格"
          show-overflow-tooltip>
        </el-table-column>

         <el-table-column
          prop="category"
          label="商品类目"
          width="120">
        </el-table-column>
        <el-table-column label="创建时间" show-overflow-tooltip>
          <template slot-scope="scopeData">
            {{dayjs(scopeData.row.create_time).format('YYYY-MM-DD HH-mm-ss')}}
          </template>
        </el-table-column>

         <el-table-column
          show-overflow-tooltip
          prop="sellPoint"
          label="商品卖点"
          width="120">
        </el-table-column>
        <el-table-column
          prop="descs"
          label="商品描述"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column label="操作" width="200" header-align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              icon="el-icon-delete"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <Pagination 
      :total="total" 
      :pageSize="pagesize" 
      @getPageIndex="getPageIndex"
      @getPageSize="getPageSize"
      ></Pagination>
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import dayjs from 'dayjs'
import { mapMutations } from 'vuex'
export default {
  
  components:{
    Pagination
  },
  data() {
    
    return {
      formInline: {
        pname: '',
        time: '',
      },
      tableData: [],
      multipleSelection: [],
      total:0,
      isSearch:false,
      listTotal:[],
      pagesize:8,
      loading:false,
      cur_page:1,
      selectids:''
    }
  },
  created(){
    this.getprojectList(1);
    
  },
  methods: {
    dayjs,
    getPageIndex(current){
      this.cur_page=current;
      if(this.isSearch){
        this.tableData=this.listTotal.slice((current-1)*8,current*8);
      }else{
        this.getprojectList(current);
      }
    },
    getPageSize(size){
      console.log('444',size);
      this.pagesize=size;
      this.getprojectList(1,size);
    },
    async getprojectList(page,size=8){
      let res=await this.$api.getprojectList({page,size});
      console.log(res);
      if(res.data.status===200){
        this.total=res.data.total;
        this.pagesize=res.data.pageSize;
        this.tableData=res.data.data;
        // console.log(this.pagesize,this.total);
      }
    },
    async getprojectSearch(search){
      this.loading=true;
      let res=await this.$api.getprojectSearch({search});
      if(res.data.status===500){
        this.$message({
          showClose: true,
          message: '暂无查询结果',
          type: 'warning',
          duration:1500
        });
      }else if(res.data.status===200){
        this.isSearch=true;
        this.listTotal=res.data.result;
        if(res.data.result.length>8){
          this.tableData=res.data.result.slice(0,8);
        }else{
          this.tableData=res.data.result;
        }
        this.total=res.data.result.length;
      }else{
         this.listTotal=[];
         this.isSearch=false;
      }
      this.loading=false;
      
      this.$nextTick(()=>{
       this.$refs.pnameInput.focus();
      })
      // this.tableData=res.data.result||[];
    }
    ,
    onSubmit() {
      // console.log('submit!',this.formInline);
      let pname=this.formInline.pname;
      if(!pname.trim()) {
        this.$message({
          showClose: true,
          message: '请输入商品名称查询',
          type: 'error',
          duration:1500
        });
        this.$nextTick(() => {
          this.$refs.pnameInput.focus()
        })
        this.isSearch=false;
        this.getprojectList(1);
        return;
      }
      this.getprojectSearch(pname);

    },
    addgoods(){
      // console.log('添加商品');
      this.$router.push('/goods/addgooditem');
      this.changeTitle('添加');
    },
    removegoods(){
      // 批量删除
      if(!this.selectids)
        return;
       this.$confirm('此操作将永久删除商品记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.batchDelete({ids:this.selectids}).then(
          (res)=>{
            console.log(res);
            // if(res.data.status===200){
            // 删除最后一页时更新分页数据
            let maxPage=Math.ceil(this.total/this.pagesize);
            console.log('当前页是',this.cur_page);
            console.log('最大页是',maxPage);
              // 最后一页是当前页
            if(this.cur_page===maxPage){
              let ids_length=this.selectids.split(',').length;
              // 如果删除最后一页的全部数据
              let pageitem_length=this.total%this.pagesize===0?this.pagesize:this.total%this.pagesize;
              console.log(ids_length,pageitem_length);
              if(ids_length===pageitem_length){
                this.cur_page=this.cur_page-1>0?this.cur_page-1:1;
              }
            }
            this.getprojectList(this.cur_page);
            // }
          }
        )
        
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
      // console.log(this.selectids);
      // this.$api.batchDelete()
    },
    ...mapMutations('product',{changeRowData:'changeRowData',changeTitle:'changeTitle'}),
    handleSelectionChange(selection) {
      console.log(selection);
      let arr=[];
      selection.forEach((ele)=>{
        arr.push(ele.id);
      })
      this.selectids=arr.join(',');
    },

    async deleteGoodItem(id){
      if(this.total%this.pagesize===1){
        this.cur_page=this.cur_page-1>0?this.cur_page-1:1;
      }
      let res=await this.$api.deleteGoodItem({id});
      console.log('删除商品',id,res);
      // if()
      if(res.status===500){
        this.$message.error('删除失败!');
      }else{
        this.getprojectList(this.cur_page);
      }

    },
    handleDetail(index,row){
      // console.log(index, row);
      this.changeRowData(row);
      this.changeTitle('查看');
      this.$router.push({name:'addgooditem'})
    },

    handleEdit(index, row) {
      // console.log(index, row);
      this.changeRowData(row);
      this.changeTitle('编辑');
      this.$router.push({name:'addgooditem'})

      
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm('此操作将永久删除商品记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteGoodItem(row.id);
        console.log(row.id);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
}
</script>

<style lang="less" scoped>
  .head{
    margin:15px;
    padding:15px;
    background-color: #fff;
    border-radius: 10px 10px 0 0;
    .search{
      
      border-bottom: 2px solid #ccc;
    }
    .managegoods{
      padding-top: 15px;
    }
  }
  .table{
    margin: 0 15px;
    .ptitle{
      // color:#000;
      cursor:pointer;
    }
    .ptitle:hover{
      color:rgb(7, 60, 135);
    }
  }
  .pagination{
    margin: 0 15px;
    position: fixed;
    // bottom:10px;
    bottom:15px;
    right:0;
    background-color: transparent;
  }
</style>